package com.ebelter.myehc.ui.activitys;

import android.content.Intent;
import android.net.Uri;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import com.ebelter.btcomlib.common.Constants;
import com.ebelter.btcomlib.models.beans.ScaleUser;
import com.ebelter.btcomlib.models.bluetooth.products.bracelet.bean.BraDb;
import com.ebelter.btcomlib.models.https.NetUtils;
import com.ebelter.btcomlib.models.https.interfaces.HttpResponse;
import com.ebelter.btcomlib.utils.MD5Utils;
import com.ebelter.btcomlib.utils.NumUtils;
import com.ebelter.btcomlib.utils.StatusBarUtil;
import com.ebelter.btcomlib.utils.ToastUtil;
import com.ebelter.btcomlib.utils.UserSpUtil;
import com.ebelter.btcomlib.utils.log.LogUtils;
import com.ebelter.myehc.R;
import com.ebelter.myehc.models.http.request.EhcNetUtils;
import com.ebelter.myehc.models.http.response.GetPersonInfoFromBT;
import com.ebelter.myehc.models.http.response.ehc.EhcLoginBt;
import com.raizlabs.android.dbflow.sql.language.Delete;
import java.util.Calendar;



//登录界面
public class LoginActivity extends EhcBaseActivity {


    public static final String TAG = "LoginActivity";



    EditText name_ed;
    EditText psw_ed;
   // private XLOneDayChartView xlOneDayChartView;

    @Override
    protected int loadLayoutById() {
        return R.layout.activity_login;
    }


    @Override
    protected void initView() {
        FV();
    }



    @Override
    protected void initData() {

        StatusBarUtil.setDarkStatusIcon(this,true);
       // saveUserDatas();

        int  ehc_phone_no = UserSpUtil.readInt(Constants.IUser.ehc_phone_no,-1);

        if (ehc_phone_no > 0){
            LogUtils.i(TAG,"-----ehc_phone_no--" + ehc_phone_no);
            name_ed.setText(ehc_phone_no+"");
        }

        String authkey = UserSpUtil.readString(Constants.IUser.AUTH_KEY,"");
        int ehc_id = UserSpUtil.readInt(Constants.IUser.ehc_id,-1);

        boolean serverIsException = getIntent().getBooleanExtra(Constants.ServerIsException,false);

        if (!TextUtils.isEmpty(authkey) && NetUtils.available() && ehc_id!=-1 && !serverIsException){
           // LogUtils.i(TAG,"authkey = "+authkey);
            //说明已经登录了
            startActivity(MainActivity.class);
            finish();
        }
    }



    private void FV() {
        name_ed = findViewById(R.id.cb1_ed);
        psw_ed = findViewById(R.id.cb2_ed);
    }

    //登录按钮
    public void login(View view) {

        if (!NetUtils.available()){
            ToastUtil.show(R.string.Network_error);
            return;
        }

        final String name=name_ed.getText().toString().trim();
        final String psw=psw_ed.getText().toString().trim();

        if (TextUtils.isEmpty(name)){
            ToastUtil.show(getString_(R.string.name_no_allow_empty));
            return;
        }
        if (TextUtils.isEmpty(psw)){
            ToastUtil.show(getString_(R.string.psw_no_empty));
            return;
        }

        showLoadingDialog(getString_(R.string.loging));


//        //www.ebelter.com
        EhcNetUtils.getInstance().ehcLogin2(this, name, psw, new HttpResponse<EhcLoginBt>() {
            @Override
            public void result(boolean isRequestSuccess, String requestDes, EhcLoginBt ehcLoginBt, String s) {
                LogUtils.i(TAG,"----------- s = " + s);
               // queryUserIsExist(ehcLoginBt);
                if (isRequestSuccess && ehcLoginBt!=null){
                    LogUtils.i(TAG,ehcLoginBt.toString());
                    if ("1".equals(ehcLoginBt.status)){//说明第一步获取用户信息成功
                        if (ehcLoginBt.result==null){
                            dissLoadingDialog();
                            return;
                        }
                        saveInfos(ehcLoginBt,psw);
                        queryUserIsExist(ehcLoginBt);
                    }else {
                        ToastUtil.show(R.string.login_fail);
                        dissLoadingDialog();
                    }
                }else {
                    ToastUtil.show(R.string.Server_unresponsive_please_try_again_later);
                    dissLoadingDialog();
                }
            }
        });

       // queryUserIsExist(null);




    }

    //保存服务器返回来的token
    private void saveInfos(EhcLoginBt ehcLoginBt,String psw) {
            UserSpUtil.writeString(Constants.IUser.ehc_token,ehcLoginBt.result.token);
            UserSpUtil.writeString(Constants.IUser.ehc_email,ehcLoginBt.result.email);
            UserSpUtil.writeString(Constants.IUser.ehc_name,ehcLoginBt.result.name);
            UserSpUtil.writeInt(Constants.IUser.ehc_age,ehcLoginBt.result.age);
            UserSpUtil.writeInt(Constants.IUser.ehc_id,ehcLoginBt.result.id);//第三方的用户id
            UserSpUtil.writeString(Constants.IUser.ehc_sex,ehcLoginBt.result.sex);

            UserSpUtil.writeInt(Constants.IUser.ehc_phone_no, NumUtils.string2Int(ehcLoginBt.result.phone_no));
            UserSpUtil.writeInt(Constants.IUser.ehc_phone_region,NumUtils.string2Int(ehcLoginBt.result.phone_region));
            UserSpUtil.writeString(Constants.IUser.ehc_p, MD5Utils.getMd5(psw));

    }




    //12345680 对应的ehcLoginBt.result.id是5
    private void queryUserIsExist(EhcLoginBt ehcLoginBt) {
        String userId = ehcLoginBt.result.id + "";
      //  String userId = "458";
      //  String userId = "5";
        EhcNetUtils.getInstance().queryUserIsExitById(this, userId, new HttpResponse<GetPersonInfoFromBT>() {
            @Override
            public void result(boolean isRequestSuccess, String requestDes, GetPersonInfoFromBT getPersonInfoFromBT, String s) {
                LogUtils.i(TAG,"---queryUserIsExist--s = "+s);
                dissLoadingDialog();
                if (!isRequestSuccess){
                    //服务器请求失败
                    ToastUtil.show(R.string.Server_unresponsive_please_try_again_later);
                    return;
                }
                Delete.table(BraDb.class);//app进来的时候删除手环同步过来的整张表
                if (getPersonInfoFromBT!=null&&getPersonInfoFromBT.resultCode==1){
                    LogUtils.i(TAG,"-----------------说明用户已经存在---------------------------");
                    LogUtils.i(TAG,"---getPersonInfoFromBT="+getPersonInfoFromBT.toString());
                    LogUtils.i(TAG,getPersonInfoFromBT.toString());
                    saveUserInfo(getPersonInfoFromBT);
                    startActivity(MainActivity.class);
                    finish();
                }else {
                    LogUtils.i(TAG,"-----------------说明用户不存在---------------------------");
                    //用户不存在就跳到保存用户信息界面
                    Intent intent = new Intent(LoginActivity.this,ModifyInfoActivity.class);
                    intent.putExtra(ModifyInfoActivity.KEY,ModifyInfoActivity.MODIFY_ADDINFO);
                    startActivityForResult(intent,99);
                }
            }
        });

    }


    //保存从倍泰后台根据用户id查询的用户信息
    private void saveUserInfo(GetPersonInfoFromBT getPersonInfoFromBT) {


        if (getPersonInfoFromBT == null || getPersonInfoFromBT.resultData == null){
            return;
        }

        //  String userid = "000f0001000001";
        long userid2 = 10000000000000L + UserSpUtil.readInt(Constants.IUser.ehc_id,0);
        UserSpUtil.writeString(Constants.IUser.USER_ID,userid2+"");

        String btId = ScaleUser.toBtId(userid2+"");
        UserSpUtil.writeString(Constants.IUser.BT_ID,btId);


        UserSpUtil.writeInt(Constants.IUser.HEIGHT,getPersonInfoFromBT.resultData.height);//前面已经判断不空了 这里不需要再次判断
        UserSpUtil.writeFloat(Constants.IUser.WEIGHT,getPersonInfoFromBT.resultData.weight);

        UserSpUtil.writeString(Constants.IUser.BIRTHDAY,getPersonInfoFromBT.resultData.birthday);

        int year=getBirthdayIntValue(getPersonInfoFromBT.resultData.birthday,0,1990);
        UserSpUtil.writeInt(Constants.IUser.YEAR,year);
        UserSpUtil.writeInt(Constants.IUser.MONTHS,getBirthdayIntValue(getPersonInfoFromBT.resultData.birthday,1,6));
        UserSpUtil.writeInt(Constants.IUser.DAY,getBirthdayIntValue(getPersonInfoFromBT.resultData.birthday,2,1));
        UserSpUtil.writeInt(Constants.IUser.AGE,getAgeByBirthday(year));

        String sex1=getPersonInfoFromBT.resultData.sex;
        int sexInt;
        if (TextUtils.equals(sex1,"1")){//服务器那边的是0未知1男2女  我这边的是0男1女
            sexInt=0;
        }else{
            sexInt=1;
        }
        UserSpUtil.writeInt(Constants.IUser.SEX,sexInt);//0男1女
        UserSpUtil.writeInt(Constants.IUser.PROFESSION,0); //0普通人1运动员
        UserSpUtil.writeFloat(Constants.IUser.IMPEDANCE,500);
        UserSpUtil.writeBoolean(Constants.IUser.IS_KG_MODEL,true);

        //LogUtils.i(TAG,"倍泰后台返回来的authkey = "+getPersonInfoFromBT.resultData.authkey);
        UserSpUtil.writeString(Constants.IUser.AUTH_KEY,getPersonInfoFromBT.resultData.authkey);

    }


    //传进来的生日格式是2018-08-08这样的格式
    public static int getBirthdayIntValue(String string,int index,int defaultValue){
        if (TextUtils.isEmpty(string)){
            return defaultValue;
        }
        String[] args = string.split("-");
        if (args.length!=3){
            return defaultValue;
        }
        return NumUtils.string2Int(args[index],defaultValue);
    }

    //根据多少年出生算出年龄来
    public static int getAgeByBirthday(int year){
        Calendar calendar = Calendar.getInstance();
        return calendar.get(Calendar.YEAR)-year;
    }


    //注册按钮
    public void registerBt(View view) {
//        Intent intent=new Intent(this,WebActivity.class);
//        //http://ehclogin.apptechclient.com/api/login
//        intent.putExtra(WebActivity.DATA_FIRST_OPEN_URL,"http://ehclogin.apptechclient.com/custom_register");
//        startActivity(intent);
        Intent intent = new Intent();
//Intent intent = new Intent(Intent.ACTION_VIEW,uri);
        intent.setAction("android.intent.action.VIEW");
        Uri content_url = Uri.parse("http://ehclogin.apptechclient.com/custom_register");
        intent.setData(content_url);
        startActivity(intent);
    }


    //忘記密碼
    public void forgotPsw(View view) {
        Intent intent = new Intent();
        intent.setAction("android.intent.action.VIEW");
        Uri content_url = Uri.parse("http://ehclogin.apptechclient.com/password/reset");
        intent.setData(content_url);
        startActivity(intent);
    }
}
